import React, { Component } from 'react'
import Activity from './../components/focusNews/Activity'
import PublishNews from './../components/focusNews/PublishNews'
import styles from './FocusNews.module.scss'
import api from './../serve/api'
import { withRouter } from 'react-router-dom'

class FocusNews extends Component {
  constructor(props) {
    super(props)
    this.state = {
      select: 0,
      tabs: [],
      news: [],
      nowNews: [], //最新发布
      total: '',
      page: 1,
      typeId: ''
    }
    this.onTab = this.onTab.bind(this)
    this.onCurrentPage = this.onCurrentPage.bind(this)
  }

  componentDidMount() {
    this.getFocusNewsTypeAll()
    this.getNowNews()
  }

  async getForcusNews(typeId, page) {
    const data = await api.listFocusNewsApi({ typeId, page, pageSize: 5 })
    if (data && data.code === '000000') {
      this.setState({
        page,
        typeId,
        news: data.result || [],
        total: data.resultNum
      })
    }
  }

  async getNowNews() {
    const data = await api.listFocusNewsApi({ page:1, pageSize: 6 })
    if (data && data.code === '000000') {
      this.setState({
        nowNews: data.result || []
      })
    }
  }

  async getFocusNewsTypeAll() {
    const data = await api.listFocusNewsTypeAll()
    if (data && data.code === '000000') {
      this.setState({
        tabs: data.result || [],
      })
      if (data.result.length > 0) {
        const first = data.result[0]
        this.getForcusNews(first.id, this.state.page)
      }
    }
  }

  onTab(item, index) {
    this.setState({
      page: 1,
      select: index
    })
    this.getForcusNews(item.id, 1)
  }

  onCurrentPage(page) {
    this.getForcusNews(this.state.typeId, page)
  }

  onItem(item) {
    this.props.history.push(`/mainPage/commonDetail/focusNews/${item.id}`)
  }

  render() {
    const { tabs, select, news, total, 
      page, nowNews } = this.state
    return (
      <div className={styles.focus_news_container}>
        <div className={styles.left_container}>
          <div className={styles.focus_tab_container}>
            {tabs.map((item, index) => {
              return (
                <div key={index} className={styles.tab_item} style={select === index ? {fontSize: 22} : {fontSize: 18}}
                  onClick={() => this.onTab(item, index)}
                >
                  {item.name || ''}
                  {select === index && <span className={styles.indicator} />}
                </div>
              )
            })}
          </div>
          <Activity
            currentPage={page}
            datas={news}
            pageTotal={total}
            onPage={currentPage => this.onCurrentPage(currentPage)}
          />
        </div>
        <div className={styles.right_container}>
          <PublishNews datas={nowNews} onItem={item => this.onItem(item)} />
        </div>
      </div>
    )
  }
}
export default withRouter(FocusNews)